const util = require('util.js')

import global from '../config/index'

const config = {
  api_base_url: `${global.http}`,
  appkey:'',
}

class HTTP {
  // 网络请求函数
  request(params) {

    if(params.url != '/v1/applet/user/login'){
      wx.showLoading({
        title: '加载中'
      });
    }
  
    return new Promise((resolve,rejects)=>{
      this._request(params,resolve,rejects)
    })
  }
  _request(params,resolve,rejects){
    let url = params.url.substring(0,5) == 'https' ? params.url : (config.api_base_url + params.url)
    var token = wx.getStorageSync('token');
    var headers = token ? {
      'auth-token':wx.getStorageSync('token')
    } : {};
    wx.request({
      url: url,
      method: params.method,
      data: params.data,
      header: headers,
      success: (res) => {
        wx.hideLoading()
        let code = res.statusCode.toString()
        // console.log(res,'shuju')
        // 判断状态码是否以2开头
        if (code.startsWith('2')) {
          // 回调函数
          // params.success(res.data)
          // console.log(res,'ressrequest')
          if(res.data.errCode == 'ERROR_TOKEN'){
            wx.hideLoading({
              success: (res) => {
                wx.showModal({
                  title: '温馨提示',
                  content: '您的登录已经过期，请重新登录',
                  success: function(){
                    wx.redirectTo({
                      url: '/pages/login/login/login',
                    })
                  },
                })
              },
            })
          }else{
            resolve(res.data)
          }
          // else{
          //   this._show_error(res.data)
          //   resolve(res.data)
          // }
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '错误信息：'+res.data+',是否返回登录页面？',
            success: function(bool){
              if(bool.confirm){
                wx.redirectTo({
                  url: '/pages/login/login/login',
                })
              }
            },
          })
          rejects()
        }
      },
      fail: (err) => {
        wx.hideLoading()
        this._show_error()
        rejects()
      },
      complete: function (res) {
      }
    })
  }

  // 错误处理函数
  _show_error(error_code) {
    if (!error_code) {
      error_code = {
        errMessage: '网络开小车了，请稍后再试'
      }
    }
    wx.showToast({
      title: error_code.errMessage,
      icon: 'none',
      duration: 2000
    })
  }
}

export {
  HTTP
}